package com.weipeep.sys.interceptor;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.weipeep.api.entity.ResultBean;
import com.weipeep.common.utils.JSONUtils;
import com.weipeep.common.utils.jwt.Decrypt;
import com.weipeep.common.utils.jwt.JWTResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class LoginInterceptor  implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ResultBean errorMsg = new ResultBean();
        String param = JSONUtils.beanToJson(showParams(request));
        String token = request.getHeader("token");
        log.info("------type:{},url:{},token:{},params:{}",request.getMethod(),request.getServletPath(),token==null?"":token,param);
        if (StringUtils.isNotEmpty(token)){
            Decrypt decrypt = new Decrypt();
            JWTResult jwtResult = decrypt.deToken(token);
            if(jwtResult.getStatus()==JWTResult.ERROR){
                errorMsg.setStatus(ResultBean.RESULT_ERROR);
                errorMsg.setMessage(jwtResult.getMsg());
            }
        }else {
            errorMsg.setStatus(ResultBean.RESULT_ERROR);
            errorMsg.setMessage("未登录");
        }
        if (errorMsg.getStatus()==ResultBean.RESULT_ERROR){
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try {
                writer = response.getWriter();
                writer.print(JSONUtils.beanToJson(errorMsg));
                return false;
            } catch (IOException e) {
                log.error("response error",e);
            } finally {
                if(writer != null){
                    writer.close();
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("-----postHandle----",request.getPathInfo());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("-----afterCompletion----",request.getPathInfo());

    }
    public static Map<String,Object> showParams(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length >0) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }
}
